package com.red.wood.module.eval.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.red.wood.common.domain.Page;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.ExportExcelUtil;
import com.red.wood.common.util.IMap;
import com.red.wood.module.eval.service.TaskAuditService;

@Controller
@RequestMapping("/evalTaskAudit")
public class TaskAuditController {
	
	private static final Log log = LogFactory.getLog(TaskAuditController.class);
	@Autowired
	private TaskAuditService service;

	/**
	 * 信息评测
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv = new ModelAndView("evalTaskAudit");
		mv.addObject("areaName", CommonUtils.valueOf(request.getParameter("areaName")));
//		mv.addObject("ircsId", CommonUtils.valueOf(request.getParameter("ircsId")));
		return mv;
	}
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getTaskAuditInfo", method = RequestMethod.POST)
	@ResponseBody
	public String getTaskAuditInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request); 
			int pageSize = Integer.parseInt(CommonUtils.valueOf(request.getParameter("pageSize")));
			String currentPage = CommonUtils.valueOf(request.getParameter("currentPage"));
			if(StringUtils.isBlank(currentPage)) {
				currentPage = "1";
			}
			Page page = Page.newBuilder(Integer.parseInt(currentPage),pageSize,null);  
			param.put("page",page);
			
			Map<String,Object> rs = service.getPageData(param);
			page.setTotalRecord(Integer.parseInt(CommonUtils.valueOf(rs.get("totalCount"))));
			List<Map<String,Object>> list = (List<Map<String, Object>>) rs.get("pageData");
			
			json.put("flag", true);
			json.put("datas",list);
			json.put("totalPages",page.getTotalPage());
			json.put("totalData", page.getTotalRecord());
			json.put("currentPage", currentPage);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "exportData",method = RequestMethod.POST)
	@ResponseBody
	public String exportData(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request);
			List<Map<String,Object>> list = service.exportData(param);
			String title = "评测审核";
			String fileName = "task_audit";
			String[] columnNames = {"企业名称","表单编号","申请业务类型","表单状态","注册地","厂商名称","机房所在地","评测申请时间"};
			String[] mapKey = {"companyName","formNum","business","statue","registerProvince","productionUnit","houseAddress","lastSubmitTime"};
			String[] columnsWidth = {"0:40","1:20","2:40","3:20","4:20","5:20","6:30","7:30"}; //列宽特殊处理,0列40字节
			ExportExcelUtil util = new ExportExcelUtil();
			String path = CommonUtils.getDataTempPath() + fileName + System.currentTimeMillis() + ".xlsx";
			util.exportExcel(title, columnNames,columnsWidth, mapKey,list, new FileOutputStream(path), ExportExcelUtil.EXCEl_FILE_2007);
			json.put("flag", true);
			json.put("path",path);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	@RequestMapping(value = "downFiles")
	public String downFiles(HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fs = null;
		OutputStream os = null;
		try {
			String path = request.getParameter("path");
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition","attachment; filename=" + path.substring(path.lastIndexOf(File.separator) + 1, path.length()));
			fs = new FileInputStream(path);
			os = response.getOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = fs.read(b)) != -1) {
				os.write(b, 0, len);
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
		}
		return null;
	}
}
